﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Agos.Utils;
using System.IO.Compression;
using System.Text.RegularExpressions;
using DeutscheRemoval.Utils;
using System.Data;
using Microsoft.Office.Interop.Excel;

namespace DeutscheRemoval
{
    public class AutomatedP
    {
        #region Fields
        private string _username = string.Empty;
        private string _password = string.Empty;

        private bool _planificata;
        private CookieContainer _cookieJar = null;
        private HttpWebRequest _request = null;
        private HttpWebResponse _response = null;
        private string _windowID = string.Empty;
        private string _postData;
        private string _timeStamp;
        private string _raspuns;
        private string _dateTime;
        private string valueContract;
        private SQLUtil _sqlU;
        private Application xlApp;
        private Workbook xlWorkBook;
        private Worksheet xlWorkSheet;
        object misValue;
        #endregion

        #region Ctor
        public AutomatedP(string u, string p, string d)
        {
            _username = u;
            _password = p;
            _dateTime = d;
        }
        #endregion

        public void Connect2()
        {
            try
            {
                _sqlU = new SQLUtil();
                string output = _sqlU.InitConnection(ConfigUtil.GetURLServer(), ConfigUtil.GetUserDB(), ConfigUtil.GetPasswordDB(), ConfigUtil.GetNameDB());
                if (output == "OK")
                {
                    string query = "select COD_VEL, CONTRATTO, DATA_QUE, SCADENZA from pratiche where cod_bas = 32 and cod_grp in (76, 77) and (SCADENZA = CONVERT(nvarchar(10),'25-'+CAST(DATEPART(month,GETDATE()) as nvarchar(10))+'-'+CAST(DATEPART(year,GETDATE()) as nvarchar(10)),103))";
                    System.Data.DataTable dt = _sqlU.ExtractValues(query);
                }
                else
                {
                    Logger.Log("non poteva connettersi al database", LogType.Error);
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex.ToString(), LogType.Error);
            }
        }

        public void Connect()
        {
            try 
	{	        
		
	}
	catch (Exception)
	{
		
		throw;
	}
            try{
                misValue = System.Reflection.Missing.Value;
                xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
                xlWorkBook = xlApp.Workbooks.Add(misValue);
                xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

                xlWorkSheet.Cells[1, 1] = "CODICE_VELINA";
                ((Range)xlWorkSheet.Cells[1, 1]).EntireColumn.NumberFormat = "@";
                xlWorkSheet.Cells[1, 2] = "CODICE_CONTRATTO";
                ((Range)xlWorkSheet.Cells[1, 2]).EntireColumn.NumberFormat = "@";
                xlWorkSheet.Cells[1, 3] = "DATA_AFFIDAMENTO";
                ((Range)xlWorkSheet.Cells[1, 3]).EntireColumn.NumberFormat = "@";
                xlWorkSheet.Cells[1, 4] = "SCADENZA_AFFIDAMENTO";
                ((Range)xlWorkSheet.Cells[1, 4]).EntireColumn.NumberFormat = "@";
                xlWorkSheet.Cells[1, 5] = "NR_RATA_INSOLUTA";
                ((Range)xlWorkSheet.Cells[1, 5]).EntireColumn.NumberFormat = "@";
                xlWorkSheet.Cells[1, 6] = "IMPORTO_RATA_INSOLUTA";
                ((Range)xlWorkSheet.Cells[1, 6]).EntireColumn.NumberFormat = "@";
                xlWorkSheet.Cells[1, 7] = "VALUTA_PAGAMENTO";
                ((Range)xlWorkSheet.Cells[1, 7]).EntireColumn.NumberFormat = "@";
                xlWorkSheet.Cells[1, 8] = "IMPORTO_PAGAMENTO";
                ((Range)xlWorkSheet.Cells[1, 8]).EntireColumn.NumberFormat = "@";

                int rowNb = 2;

                _sqlU = new SQLUtil();
                string output = _sqlU.InitConnection(ConfigUtil.GetURLServer(), ConfigUtil.GetUserDB(), ConfigUtil.GetPasswordDB(), ConfigUtil.GetNameDB());
                if (output == "OK")
                {
                    string query = "select COD_VEL, CONTRATTO, DATA_QUE, SCADENZA from pratiche where cod_bas = 32 and cod_grp in (76, 77) and ( (cap_aff_euro + int_aff_euro + spe_aff_euro) - (cap_rec_euro + int_rec_euro + spe_rec_euro) <= 0 ) and (SCADENZA >= convert(nvarchar(10),GETDATE(),105)) ";
                    System.Data.DataTable dt = _sqlU.ExtractValues(query);
                    foreach (DataRow r in dt.Rows)
                    {
                        valueContract = r[1].ToString();
                        Agos.Utils.Logger.Log("process start / login to website", LogType.Operation);
                        _raspuns = LoginStep();
                        if (_raspuns.Contains("reject.html"))
                        {
                            // response = LoginFailStep();
                        }
                        else if (_raspuns.Contains("WEBarte/ArTe.jsp"))
                        {
                            _raspuns = LoginSuccedStep1();
                            _raspuns = LoginSuccedStep2();
                            _raspuns = LoginSuccedStep3();
                            _raspuns = GoToGestioneMandati();
                            //_raspuns = GotoSpecificValue("PT0000003708985200");
                            _raspuns = GotoSpecificValue(valueContract);
                            string[] addwidgS = _raspuns.Split(new string[] { "addWidget" }, StringSplitOptions.RemoveEmptyEntries);
                            bool cont = false;
                            int count = 0;
                            string a = string.Empty;

                            foreach (string s in addwidgS)
                            {
                                if (s.Contains(valueContract))
                                {
                                    cont = true;
                                    count++;
                                    if (count == 2)
                                        break;
                                }
                            }
                            if (count >= 2)
                            {
                                _raspuns = GoToVisualizza();

                                List<string[]> l = ParseResponse(_raspuns);

                                int colNb = 1;
                                foreach (string[] str in l)
                                {
                                    if (str[3] != "00.00.0000" && r.ItemArray[2].ToString() != "00.00.0000")
                                    {
                                        DateTime date1 = Convert.ToDateTime(str[3].Replace('.', '-'), new System.Globalization.CultureInfo("it-IT", true));
                                        DateTime date2 = Convert.ToDateTime(r.ItemArray[2].ToString().Split(' ')[0].Replace('.', '-'), new System.Globalization.CultureInfo("it-IT", true));
                                        if (date1 > date2)
                                        {
                                            colNb = 1;
                                            foreach (object o in r.ItemArray)
                                            {
                                                xlWorkSheet.Cells[rowNb, colNb] = o.ToString().Split(' ')[0];
                                                colNb++;
                                            }
                                            for (int i = 0; i < str.Length; i++)
                                            {
                                                if (i != 2 && i != 3)
                                                {
                                                    xlWorkSheet.Cells[rowNb, colNb] = str[i].ToString();

                                                    colNb++;
                                                }
                                                else if (i == 3)
                                                {
                                                    //Range rg = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[rowNb, colNb];
                                                    //rg.NumberFormat = "DD/MM/YYYY";
                                                    xlWorkSheet.Cells[rowNb, colNb] = str[i].ToString();

                                                    colNb++;
                                                }
                                            }
                                            rowNb++;
                                        }
                                    }
                                }
                            }
                        }
                        //rowNb++;
                    }
                    xlWorkBook.SaveAs(ConfigUtil.GetExcelPath()+ConfigUtil.GetExcelName(), Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

                }
                else
                {
                    Logger.Log("non poteva connettersi al database", LogType.Error);
                }
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex.ToString());
                Logger.Log(ex.ToString(), LogType.Error);
                xlWorkBook.Close(true, misValue, misValue);
                xlApp.Quit();

                releaseObject(xlWorkSheet);
                releaseObject(xlWorkBook);
                releaseObject(xlApp);
                Console.WriteLine("Exception");
            }
            finally
            {
                string output = _sqlU.CloseConnection();
                xlWorkBook.Close(true, misValue, misValue);
                xlApp.Quit();

                releaseObject(xlWorkSheet);
                releaseObject(xlWorkBook);
                releaseObject(xlApp);
                Console.WriteLine("finish");
            }
        }

        private List<string[]> ParseResponse(string _raspuns)
        {
            int index = _raspuns.IndexOf("\"wdg_DettaglioRateDaRecuperare\"");
            string substr = _raspuns.Substring(index - 13, 2000);
            int index2 = substr.IndexOf(">");
            int index3 = substr.IndexOf("</TEXTAREA>");
            string substr2 = substr.Substring(index2 + 1, index3 - index2 - 1);

            string[] values = substr2.Replace("\r", "").Split('\n');
            List<string[]> l = new List<string[]>();
            for (int i = 0; i < values.Length; i++)
            {
                if (values[i] != "")
                {
                    string[] indValues = values[i].Split(' ');
                    string[] v = new string[5];
                    int j = 0;
                    foreach (string s in indValues)
                    {
                        if (!string.IsNullOrEmpty(s))
                        {
                            v[j++] = s;
                        }

                    }
                    l.Add(v);
                }
            }
            return l;
        }

        public string LoginSuccedStep1()
        {
            string ret = string.Empty;
            try
            {
                _request = null;
                _request = (HttpWebRequest)WebRequest.Create("https://www.new-pronto.prestitempo.it/WEBarte/ArTe.jsp");
                //set the post method
                _request.AllowAutoRedirect = true;
                //_request.ServicePoint.Expect100Continue = false;
                _request.Method = "GET";
                //set the cookie container
                _request.CookieContainer = _cookieJar;
                WebHeaderCollection wc = new WebHeaderCollection();
                wc.Add("Accept-Language", "en-us");
                wc.Add("Accept-Encoding", "gzip,deflate");
                wc.Add("Cache-Control", "no-cache");
                _request.Headers = wc;
                _request.Referer = "https://www.new-pronto.prestitempo.it/";
                _request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; InfoPath.3; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)";
                _request.KeepAlive = true;
                _request.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
                _response = (HttpWebResponse)_request.GetResponse();
                Stream str = _response.GetResponseStream();
                StreamReader sr = new StreamReader(str);
                ret = UnZip(str);
                //connection complete
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
            return ret;
        }

        public string LoginSuccedStep2()
        {
            string ret = string.Empty;
            try
            {

                _request = null;
                // TimeSpan ts = DateTime.Now - DateTime.ParseExact("01/01/1970", "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
                _request = (HttpWebRequest)WebRequest.Create("https://www.new-pronto.prestitempo.it/WEBarte/ArTe/jsp/ie4/ATServices.jsp?webappPath=/WEBarte/&screenResolution=HR");
                //_request = (HttpWebRequest)WebRequest.Create("https://www.new-pronto.prestitempo.it/WEBarte/servlet/com.accenture.atservices.servlets.ATDispatcher?ATDataTransferField=&ATUserEvent=&ATUserEventType=&ATCurrentPageTimestamp=&Browser=ie4&Attributes=true&WindowID=" + (ts.TotalMilliseconds.ToString().Contains(",") ? ts.TotalMilliseconds.ToString().Substring(0, ts.TotalMilliseconds.ToString().IndexOf(",")) : ts.TotalMilliseconds.ToString()) + "&ATDisplayCurrency=");
                //set the post method
                _request.Method = "GET";
                _request.AllowAutoRedirect = true;
                _request.CookieContainer = _cookieJar;
                _request.KeepAlive = true;
                WebHeaderCollection wc = new WebHeaderCollection();
                wc.Add("Accept-Encoding", "gzip,deflate");
                wc.Add("Accept-Language", "en-us");
                _request.Headers = wc;
                _request.Referer = "https://www.new-pronto.prestitempo.it/WEBarte/ArTe.jsp";
                _request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; InfoPath.3; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)";
                _request.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
                _response = (HttpWebResponse)_request.GetResponse();
                Stream str = _response.GetResponseStream();
                StreamReader sr = new StreamReader(str);
                ret = UnZip(str);

            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
            return ret;
        }

        public string LoginSuccedStep3()
        {
            string ret = string.Empty;
            try
            {

                _request = null;
                TimeSpan ts = DateTime.Now - DateTime.ParseExact("01/01/1970", "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
                _windowID = (ts.TotalMilliseconds.ToString().Contains(".") ? ts.TotalMilliseconds.ToString().Substring(0, ts.TotalMilliseconds.ToString().IndexOf(".")) : ts.TotalMilliseconds.ToString());
                // _request = (HttpWebRequest)WebRequest.Create("https://www.new-pronto.prestitempo.it/WEBarte/code/ps/home/PSHome_ie4.js");
                _request = (HttpWebRequest)WebRequest.Create("https://www.new-pronto.prestitempo.it/WEBarte/servlet/com.accenture.atservices.servlets.ATDispatcher?ATDataTransferField=&ATUserEvent=&ATUserEventType=&ATCurrentPageTimestamp=&Browser=ie4&Attributes=true&WindowID=" + _windowID + "&ATDisplayCurrency=");
                //set the post method
                _request.Method = "GET";
                _request.AllowAutoRedirect = true;
                _request.CookieContainer = _cookieJar;
                _request.KeepAlive = true;
                WebHeaderCollection wc = new WebHeaderCollection();
                wc.Add("Accept-Encoding", "gzip,deflate");
                wc.Add("Accept-Language", "en-us");
                _request.Headers = wc;
                _request.Referer = "https://www.new-pronto.prestitempo.it/WEBarte/ArTe/jsp/ie4/ATServices.jsp?webappPath=/WEBarte/&screenResolution=HR";
                _request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; InfoPath.3; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)";
                _request.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
                _response = (HttpWebResponse)_request.GetResponse();
                Stream str = _response.GetResponseStream();
                StreamReader sr = new StreamReader(str);
                ret = UnZip(str);
                _timeStamp = GetTimeStamp(ret);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
            return ret;
        }

        private string GetTimeStamp(string response)
        {
            string ret = string.Empty;
            try
            {
                if (!string.IsNullOrEmpty(response))
                {
                    int start = response.IndexOf("ATTStamp=\"");
                    start = start + "ATTStamp=\"".Length;
                    ret = response.Substring(start, response.Substring(start, 100).IndexOf("\";"));
                }
            }
            catch (Exception ex)
            {
                Logger.Log("Time Stamp extract failed! Reason: " + ex.Message, LogType.Error);
            }
            return ret;
        }

        private string GoToGestioneMandati()
        {
            string ret = string.Empty;
            try
            {
                _request = null;
                _request = (HttpWebRequest)WebRequest.Create("https://www.new-pronto.prestitempo.it/WEBarte/servlet/com.accenture.atservices.servlets.ATDispatcher");
                _request.AllowAutoRedirect = true;
                _request.Method = "POST";
                _request.CookieContainer = _cookieJar;
                WebHeaderCollection whc = new WebHeaderCollection();
                whc.Add("Accept-Encoding", "gzip,defalte");
                whc.Add("Accept-Language", "en-us");
                whc.Add("Cache-Control", "no-cache");
                _request.Headers = whc;
                _request.Referer = "https://www.new-pronto.prestitempo.it/WEBarte/ArTe/jsp/ie4/ATServices.jsp?webappPath=/WEBarte/&screenResolution=HR";
                _request.ContentType = "application/x-www-form-urlencoded";
                //content_request.ContentLength = 248;
                _request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; InfoPath.3; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)";
                _request.KeepAlive = true;
                _postData = "ATDataTransferField=MenuConversazioni%3Dtrue%25A7false%25A7%25BFGestione%2520Mandati&ATUserEvent=Launch&ATUserEventType=ACT&ATCurrentPageTimestamp=" + _timeStamp + "&Browser=ie4&Attributes=true&WindowID=" + _windowID + "&ATDisplayCurrency=0";
                byte[] data = Encoding.ASCII.GetBytes(_postData);
                Stream streamData = _request.GetRequestStream();
                streamData.Write(data, 0, data.Length);
                streamData.Flush();
                streamData.Close();
                _response = (HttpWebResponse)_request.GetResponse();
                Stream str = _response.GetResponseStream();
                ret = UnZip(str);
                _timeStamp = GetTimeStamp(ret);
            }
            catch (Exception ex)
            {
                Logger.Log(ex.ToString(), LogType.Error);
            }
            return ret;

        }

        private string GotoSpecificValue(string value)
        {
            string ret = string.Empty;
            try
            {
                _request = null;
                _request = (HttpWebRequest)WebRequest.Create("https://www.new-pronto.prestitempo.it/WEBarte/servlet/com.accenture.atservices.servlets.ATDispatcher");
                _request.AllowAutoRedirect = true;
                _request.Method = "POST";
                _request.CookieContainer = _cookieJar;
                WebHeaderCollection whc = new WebHeaderCollection();
                whc.Add("Accept-Encoding", "gzip,defalte");
                whc.Add("Accept-Language", "en-us");
                whc.Add("Cache-Control", "no-cache");
                _request.Headers = whc;
                _request.Referer = "https://www.new-pronto.prestitempo.it/WEBarte/ArTe/jsp/ie4/ATServices.jsp?webappPath=/WEBarte/&screenResolution=HR";
                _request.ContentType = "application/x-www-form-urlencoded";
                // _request.ContentLength = 263;
                _request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; InfoPath.3; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)";
                _request.KeepAlive = true;
                _postData = "ATDataTransferField=NumeroContratto%3Dtrue%25A7true%25A7false%25A7true%25A7false%25A7" + value + "&ATUserEvent=Cerca&ATUserEventType=ACT&ATCurrentPageTimestamp=" + _timeStamp + "&Browser=ie4&Attributes=true&WindowID=" + _windowID + "&ATDisplayCurrency=0";
                byte[] data = Encoding.ASCII.GetBytes(_postData);
                Stream streamData = _request.GetRequestStream();
                streamData.Write(data, 0, data.Length);
                streamData.Flush();
                streamData.Close();
                _response = (HttpWebResponse)_request.GetResponse();
                Stream str = _response.GetResponseStream();
                ret = UnZip(str);
                _timeStamp = GetTimeStamp(ret);
            }
            catch (Exception ex)
            {
                Logger.Log(ex.ToString(), LogType.Error);
            }
            return ret;
        }

        private string GoToVisualizza()
        {
            string ret = string.Empty;
            try
            {
                _request = null;
                _request = (HttpWebRequest)WebRequest.Create("https://www.new-pronto.prestitempo.it/WEBarte/servlet/com.accenture.atservices.servlets.ATDispatcher");
                _request.AllowAutoRedirect = true;
                _request.Method = "POST";
                _request.CookieContainer = _cookieJar;
                WebHeaderCollection whc = new WebHeaderCollection();
                whc.Add("Accept-Encoding", "gzip,defalte");
                whc.Add("Accept-Language", "en-us");
                whc.Add("Cache-Control", "no-cache");
                _request.Headers = whc;
                _request.Referer = "https://www.new-pronto.prestitempo.it/WEBarte/ArTe/jsp/ie4/ATServices.jsp?webappPath=/WEBarte/&screenResolution=HR";
                _request.ContentType = "application/x-www-form-urlencoded";
                // _request.ContentLength = 342;
                _request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; InfoPath.3; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)";
                _request.KeepAlive = true;
                _postData = "ATDataTransferField=ActionArea%3Dtrue%25A7true%25A7true%25A7true%25A7true%25A7true%25A7true%25A7false%25A7true%25A7true%25A7%26RisultatoRicerca%3Dtrue%25A7false%25A7%25A70%25A70&ATUserEvent=Visualizza&ATUserEventType=ACT&ATCurrentPageTimestamp=" + _timeStamp + "&Browser=ie4&Attributes=true&WindowID=" + _windowID + "&ATDisplayCurrency=0";
                byte[] data = Encoding.ASCII.GetBytes(_postData);
                Stream streamData = _request.GetRequestStream();
                streamData.Write(data, 0, data.Length);
                streamData.Flush();
                streamData.Close();
                _response = (HttpWebResponse)_request.GetResponse();
                Stream str = _response.GetResponseStream();
                ret = UnZip(str);
                _timeStamp = GetTimeStamp(ret);
            }
            catch (Exception ex)
            {
                Logger.Log(ex.ToString(), LogType.Error);
            }
            return ret;
        }

        private string GoToDiary()
        {
            string ret = string.Empty;
            try
            {
                _request = null;
                _request = (HttpWebRequest)WebRequest.Create("https://www.new-pronto.prestitempo.it/WEBarte/servlet/com.accenture.atservices.servlets.ATDispatcher");
                _request.AllowAutoRedirect = true;
                _request.Method = "POST";
                _request.CookieContainer = _cookieJar;
                WebHeaderCollection whc = new WebHeaderCollection();
                whc.Add("Accept-Encoding", "gzip,defalte");
                whc.Add("Accept-Language", "en-us");
                whc.Add("Cache-Control", "no-cache");
                _request.Headers = whc;
                _request.Referer = "https://www.new-pronto.prestitempo.it/WEBarte/ArTe/jsp/ie4/ATServices.jsp?webappPath=/WEBarte/&screenResolution=HR";
                _request.ContentType = "application/x-www-form-urlencoded";
                // _request.ContentLength = 342;
                _request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; InfoPath.3; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)";
                _request.KeepAlive = true;
                _postData = "ATDataTransferField=NewToponimo%3Dtrue%25A7true%25A7true%25A7true%25A7true%25A7%25A7%25A7%25A7&ATUserEvent=tdma0006&ATUserEventType=NAV&ATCurrentPageTimestamp="+_timeStamp+"&Browser=ie4&Attributes=true&WindowID="+_windowID+"&ATDisplayCurrency=0";
                byte[] data = Encoding.ASCII.GetBytes(_postData);
                Stream streamData = _request.GetRequestStream();
                streamData.Write(data, 0, data.Length);
                streamData.Flush();
                streamData.Close();
                _response = (HttpWebResponse)_request.GetResponse();
                Stream str = _response.GetResponseStream();
                ret = UnZip(str);
                _timeStamp = GetTimeStamp(ret);
            }
            catch (Exception ex)
            {
                Logger.Log(ex.ToString(), LogType.Error);
            }
            return ret;
        }

        private string LoginStep()
        {
            string ret = string.Empty;
            try
            {
                //LOGIN PAGE
                _cookieJar = new CookieContainer();
                _request = (HttpWebRequest)WebRequest.Create("https://www.new-pronto.prestitempo.it/siteminderagent/forms/login.fcc");
                _request.AllowAutoRedirect = false;
                _request.ServicePoint.Expect100Continue = false;
                _request.Method = "POST";
                _request.CookieContainer = _cookieJar;
                WebHeaderCollection wc = new WebHeaderCollection();
                wc.Add("Accept-Language", "en-us");
                wc.Add("Accept-Encoding", "gzip,deflate");
                wc.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
                _request.Headers = wc;
                _request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; GTB6.5; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
                _request.KeepAlive = true;
                _request.Accept = "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/vnd.ms-excel, */*";
                _request.ContentType = "application/x-www-form-urlencoded";
                string postData = "USER=" + _username + "&PASSWORD=" + _password + "&target=%2FWEBarte%2FArTe.jsp&smauthreason=0";
                byte[] data = Encoding.ASCII.GetBytes(postData);
                Stream streamData = _request.GetRequestStream();
                streamData.Write(data, 0, data.Length);
                streamData.Flush();
                streamData.Close();
                //get the response
                _response = (HttpWebResponse)_request.GetResponse();
                Stream str = _response.GetResponseStream();
                StreamReader sr = new StreamReader(str);
                ret = sr.ReadToEnd();
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
            return ret;
        }

        private static string UnZip(Stream str)
        {
            System.Text.StringBuilder sB = new StringBuilder("");
            try
            {
                byte[] byteArray = new byte[10000000];

                GZipStream sr = new GZipStream(str, CompressionMode.Decompress);

                int rByte = 0;
                try
                {
                    rByte = sr.Read(byteArray, 0, byteArray.Length - 1);
                }
                catch (Exception gzError)
                {
                    throw gzError;
                }

                sB = new System.Text.StringBuilder(rByte);
                for (int i = 0; i < rByte; i++)
                {
                    sB.Append((char)byteArray[i]);
                }
                sr.Close();
                sr.Dispose();
                str.Close();
                str.Dispose();
            }
            catch
            {
                Agos.Utils.Logger.Log("Unzip process failed", LogType.Error);
            }
            return sB.ToString();
        }

        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                Agos.Utils.Logger.Log(ex.ToString(), LogType.Error);
            }
            finally
            {
                GC.Collect();
            }
        }
    }
}
